import React, { useState, useEffect } from 'react';
import { 
  View, 
  Text, 
  TextInput, 
  TouchableOpacity, 
  StyleSheet, 
  FlatList, 
  Image, 
  ActivityIndicator,
  Alert
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { FontAwesome } from '@expo/vector-icons';
import { auth } from '../utils/auth';
import { api } from '../utils/api';
import { ECOMMERCE_API } from '../config/apiConfig';

const ProductListScreen = ({ navigation }) => {
  const [products, setProducts] = useState([]);
  const [filteredProducts, setFilteredProducts] = useState([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);

  // 初始化数据
  useEffect(() => {
    // 检查登录状态
    checkLoginStatus();
    // 加载商品数据
    fetchProducts();
  }, []);

  // 监听搜索关键词变化
  useEffect(() => {
    filterProducts();
  }, [searchQuery, products]);

  // 检查登录状态
  const checkLoginStatus = async () => {
    try {
      const isLoggedIn = await auth.isLoggedIn();
      if (!isLoggedIn) {
        navigation.replace('LoginScreen');
      }
    } catch (error) {
      console.error('检查登录状态失败:', error);
      navigation.replace('LoginScreen');
    }
  };

  // 获取商品列表
  const fetchProducts = async () => {
    setIsLoading(true);
    try {
      const response = await api.get(ECOMMERCE_API.PRODUCTS);
      setProducts(response);
      setFilteredProducts(response);
    } catch (error) {
      console.error('获取商品列表失败:', error);
      Alert.alert('失败', '获取商品列表失败，请稍后再试');
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  };

  // 搜索商品
  const searchProducts = async () => {
    if (!searchQuery.trim()) {
      fetchProducts();
      return;
    }

    setIsLoading(true);
    try {
      const response = await api.get(ECOMMERCE_API.PRODUCT_SEARCH, { keyword: searchQuery.trim() });
      setFilteredProducts(response);
    } catch (error) {
      console.error('搜索商品失败:', error);
      Alert.alert('失败', '搜索商品失败，请稍后再试');
    } finally {
      setIsLoading(false);
    }
  };

  // 根据搜索关键词过滤商品
  const filterProducts = () => {
    if (!searchQuery.trim()) {
      setFilteredProducts(products);
      return;
    }

    const filtered = products.filter(product => 
      product.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      product.description.toLowerCase().includes(searchQuery.toLowerCase())
    );
    setFilteredProducts(filtered);
  };

  // 刷新商品列表
  const handleRefresh = () => {
    setIsRefreshing(true);
    fetchProducts();
  };

  // 处理用户登出
  const handleLogout = async () => {
    Alert.alert(
      '退出登录',
      '确定要退出登录吗？',
      [
        { text: '取消', style: 'cancel' },
        { 
          text: '确定', 
          onPress: async () => {
            try {
              await auth.logout();
              navigation.replace('LoginScreen');
            } catch (error) {
              console.error('登出失败:', error);
              Alert.alert('失败', '退出登录失败，请稍后再试');
            }
          }
        }
      ]
    );
  };

  // 查看商品详情
  const viewProductDetails = (product) => {
    // 在实际项目中，这里可以导航到商品详情页面
    Alert.alert('商品详情', 
      `${product.name}\n\n价格: ¥${product.price}\n\n库存: ${product.stock}\n\n描述: ${product.description}`
    );
  };

  // 添加到购物车
  const addToCart = (product) => {
    Alert.alert('添加成功', `${product.name} 已添加到购物车`);
  };

  // 渲染商品项
  const renderProductItem = ({ item }) => (
    <TouchableOpacity 
      style={styles.productItem} 
      onPress={() => viewProductDetails(item)}
      activeOpacity={0.7}
    >
      <View style={styles.productImageContainer}>
        {/* 使用占位图 */}
        <View style={[styles.productImage, { backgroundColor: getRandomColor() }]}>
          <Text style={styles.productImageText}>{item.name.charAt(0)}</Text>
        </View>
      </View>
      <View style={styles.productInfo}>
        <Text style={styles.productName} numberOfLines={1}>{item.name}</Text>
        <Text style={styles.productDescription} numberOfLines={2}>{item.description}</Text>
        <Text style={styles.productPrice}>¥{item.price}</Text>
        <View style={styles.productActions}>
          <TouchableOpacity 
            style={styles.addToCartButton}
            onPress={() => addToCart(item)}
          >
            <FontAwesome name="shopping-cart" size={16} color="white" />
            <Text style={styles.addToCartButtonText}>加入购物车</Text>
          </TouchableOpacity>
        </View>
      </View>
    </TouchableOpacity>
  );

  // 生成随机颜色作为商品图片占位符
  const getRandomColor = () => {
    const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA5A5', '#98D8C8'];
    return colors[Math.floor(Math.random() * colors.length)];
  };

  // 渲染列表头部
  const renderListHeader = () => (
    <View style={styles.searchContainer}>
      <View style={styles.searchInputContainer}>
        <FontAwesome name="search" size={16} color="#666" style={styles.searchIcon} />
        <TextInput
          style={styles.searchInput}
          placeholder="搜索商品..."
          value={searchQuery}
          onChangeText={setSearchQuery}
          onSubmitEditing={searchProducts}
          returnKeyType="search"
        />
        {searchQuery.trim() !== '' && (
          <TouchableOpacity 
            style={styles.clearButton}
            onPress={() => setSearchQuery('')}
          >
            <FontAwesome name="times-circle" size={16} color="#666" />
          </TouchableOpacity>
        )}
      </View>
      {searchQuery.trim() !== '' && (
        <TouchableOpacity 
          style={styles.searchButton}
          onPress={searchProducts}
          disabled={isLoading}
        >
          {isLoading ? (
            <ActivityIndicator size="small" color="white" />
          ) : (
            <Text style={styles.searchButtonText}>搜索</Text>
          )}
        </TouchableOpacity>
      )}
    </View>
  );

  // 渲染列表空状态
  const renderEmptyList = () => (
    <View style={styles.emptyContainer}>
      <FontAwesome name="shopping-bag" size={50} color="#ccc" />
      <Text style={styles.emptyText}>
        {isLoading ? '正在加载商品...' : '暂无商品'}
      </Text>
      {!isLoading && (
        <TouchableOpacity 
          style={styles.retryButton}
          onPress={fetchProducts}
        >
          <Text style={styles.retryButtonText}>重新加载</Text>
        </TouchableOpacity>
      )}
    </View>
  );

  return (
    <SafeAreaView style={styles.container}>
      {/* 头部 */}
      <View style={styles.header}>
        <Text style={styles.headerTitle}>商品列表</Text>
        <TouchableOpacity style={styles.logoutButton} onPress={handleLogout}>
          <FontAwesome name="sign-out" size={18} color="#666" />
        </TouchableOpacity>
      </View>

      {/* 商品列表 */}
      <FlatList
        data={filteredProducts}
        renderItem={renderProductItem}
        keyExtractor={item => item.id.toString()}
        contentContainerStyle={styles.productList}
        showsVerticalScrollIndicator={false}
        ListHeaderComponent={renderListHeader}
        ListEmptyComponent={renderEmptyList}
        refreshing={isRefreshing}
        onRefresh={handleRefresh}
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
    backgroundColor: 'white',
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  logoutButton: {
    padding: 8,
  },
  searchContainer: {
    padding: 16,
    backgroundColor: 'white',
  },
  searchInputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 8,
  },
  searchIcon: {
    marginRight: 8,
  },
  searchInput: {
    flex: 1,
    fontSize: 15,
    color: '#333',
    padding: 0,
  },
  clearButton: {
    padding: 4,
  },
  searchButton: {
    backgroundColor: '#007AFF',
    borderRadius: 8,
    paddingVertical: 10,
    alignItems: 'center',
    marginTop: 12,
  },
  searchButtonText: {
    color: 'white',
    fontSize: 15,
    fontWeight: '500',
  },
  productList: {
    paddingBottom: 16,
  },
  productItem: {
    flexDirection: 'row',
    backgroundColor: 'white',
    borderRadius: 8,
    marginHorizontal: 16,
    marginTop: 12,
    padding: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 2,
  },
  productImageContainer: {
    width: 80,
    height: 80,
    marginRight: 12,
  },
  productImage: {
    width: '100%',
    height: '100%',
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  productImageText: {
    color: 'white',
    fontSize: 24,
    fontWeight: 'bold',
  },
  productInfo: {
    flex: 1,
    justifyContent: 'space-between',
  },
  productName: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333',
    marginBottom: 4,
  },
  productDescription: {
    fontSize: 13,
    color: '#666',
    marginBottom: 8,
    lineHeight: 18,
  },
  productPrice: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#FF6B6B',
  },
  productActions: {
    flexDirection: 'row',
    marginTop: 8,
  },
  addToCartButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#4ECDC4',
    borderRadius: 4,
    paddingHorizontal: 12,
    paddingVertical: 6,
  },
  addToCartButtonText: {
    color: 'white',
    fontSize: 13,
    fontWeight: '500',
    marginLeft: 4,
  },
  emptyContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    padding: 40,
  },
  emptyText: {
    marginTop: 16,
    fontSize: 16,
    color: '#666',
  },
  retryButton: {
    marginTop: 16,
    backgroundColor: '#007AFF',
    paddingHorizontal: 16,
    paddingVertical: 10,
    borderRadius: 8,
  },
  retryButtonText: {
    color: 'white',
    fontSize: 15,
    fontWeight: '500',
  },
});

export default ProductListScreen;